'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const {
		articleId,
		userId
	} = event;

	const user = await db.collection("user").doc(userId).get();
	const complimentsList = user.data[0].thumbs_up_article_ids;

	let msg = '';
	let compliments_id = null;
	let thumbsNumber = null

	if (complimentsList.includes(articleId)) {
		//取消点赞
		compliments_id = dbCmd.pull(articleId)
		thumbsNumber = -1
		msg = '取消点赞'
	} else {
		//点赞
		compliments_id = dbCmd.addToSet(articleId)
		thumbsNumber = 1
		msg = '点赞成功'
	}

	await db.collection('user').doc(userId).update({
		thumbs_up_article_ids: compliments_id
	})

	//修改点赞数量
	await db.collection('article').doc(articleId).update({
		thumbs_up_count: dbCmd.inc(thumbsNumber)
	})

	//返回数据给客户端
	return {
		code: 0,
		data: {
			msg
		}
	}
};
